import subprocess
import sys

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from flask import request, jsonify  # ✅ 确保导入 request
import asyncio
import os

from api.models import AlgorithmAPI

from scheduling.dag.graph import Graph, Node, Edge
from scheduling.paradag import dag_run, SequentialProcessor, FullSelector
import json
def message(sender, msg_type, msg):
    text = {
        'sender': sender,
        'contentType': msg_type,
        'content': msg,
    }
    return text



async def executeDAG(data):
    nodes_data = json.loads(data["nodes"])
    edges_data = json.loads(data["edges"])
    executor = get_executor()
    nodes_map = {}
    edges = []
    for n in nodes_data:
        if 'isTrue' in n:
            node = Node(n['id'], n['name'], n['params'], n['isTrue'])
        else:
            node = Node(n['id'], n['name'], n['params'], True)
        nodes_map[n['id']] = node
    for e in edges_data:
        edges.append(Edge(e['source'], e['target']))
    graph = Graph(nodes_map, edges)
    if graph.validateGraph() == False:
        loop = asyncio.get_event_loop()
        task = loop.create_task(self.notifier.send_json(message('system', 'ERROR', f'非法的DAG图')))
        await task
        return
    log = await dag_run(graph.graph, processor=SequentialProcessor(), executor=executor)
    return log

# async def run_algorithm():
#     data = request.get_json()
#     result = await executeDAG(data)
#
#     return jsonify({
#         "status": "success",
#         "message": "算法执行完毕",
#         "result": json.loads(json.dumps(result, default=lambda o: o.__dict__))  # ✅ 自动转换对象
#     })
def get_executor():
    from scheduling.dag.executer import CVExecuter
    return CVExecuter()
def get_operations():
    from scheduling.dag.executer import OPERATIONS
    return OPERATIONS


def get_algorithm(request, algorithm_id):
    """根据算法 ID 获取 API 配置信息"""
    api = AlgorithmAPI.objects.filter(algorithm_id=algorithm_id, is_deleted=False).first()
    if not api:
        return JsonResponse({"status": "error", "message": "API 配置信息未找到"}, status=404)

    return JsonResponse({
        "status": "success",
        "api": {
            "id": api.id,
            "algorithm_id": api.algorithm.id,
            "url": api.url,
            "description": api.description,
            "is_deleted": api.is_deleted
        }
    })
@csrf_exempt
def start_algorithm_service(request):
    """启动 DAG 算法 API 服务"""
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            port = data.get('port')

            if not port:
                return JsonResponse({"status": "error", "message": "端口号不能为空"}, status=400)

            python_exec = sys.executable  # 获取当前 Python 解释器路径
            script_path = os.path.join(os.path.dirname(__file__), 'api.py')

            # ✅ 显式传递 Django 设置环境变量
            env = os.environ.copy()
            env['DJANGO_SETTINGS_MODULE'] = 'application.settings'  # 🚀 确保子进程使用 `application.settings`

            subprocess.Popen([python_exec, script_path, str(port)], env=env)

            return JsonResponse({"status": "success", "message": f"DAG API 服务已启动于端口 {port}"})
        except Exception as e:
            return JsonResponse({"status": "error", "message": str(e)}, status=500)

    return JsonResponse({"status": "error", "message": "仅支持 POST 请求"}, status=405)
